import { useUserStore } from '@/stores/user'
import Cookies from 'js-cookie'
import { globalConfig } from '@vipl520/utils'

const TokenKey = 'access-token'

// 获取hash中的查询参数
export function getHashQuery(name: string) {
  const hash = window.location.hash
  if (hash && hash.includes('?')) {
    const hashQuery = hash.split('?')[1]
    return new URLSearchParams(hashQuery).get(name)
  }
  return null
}

export function getPlaid() {
  // 先尝试获取p参数，如果没有再尝试获取plaid参数
  return getHashQuery('p') || getHashQuery('plaid')
}

export function getAppid() {
  return getHashQuery('appid') || getQueryByName('appid') || window.dkSys.appid
}

export function getToken(): any {
  return Cookies.get(TokenKey)
}

export function setToken(token: string) {
  return Cookies.set(TokenKey, token)
}

export function clearToken() {
  return Cookies.remove(TokenKey)
}

export function getQueryByNameHash(name: any) {
  const hashQuery = location.hash.split('?')[1]
  return hashQuery ? new URLSearchParams(hashQuery).get(name) : null
}

// 获取URL查询参数（不包括hash部分）
export function getQueryByName(name: string) {
  return new URLSearchParams(location.search).get(name)
}

export function auth(name: string | string[]) {
  const userStore = useUserStore()
  const userRoles = userStore.roles as string[]

  if (typeof name === 'string') {
    return userRoles?.includes(name)
  } else if (Array.isArray(name)) {
    return name.some((role) => userRoles?.includes(role))
  }
  return false
}

export function updateGlobalConfig() {
  globalConfig.ApiUrl = import.meta.env.VITE_BASE_URL
  globalConfig.AccessToken = getToken()
  globalConfig.Plaid = Number(getPlaid()) || 0
  globalConfig.AddonName = import.meta.env.VITE_BASE_ADDON_NAME
}

export function getDev(): boolean {
  return import.meta.env.DEV
}
